// lib/views/stock_list/stock_list_view.dart
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:stock_helper/modules/discover/pages/stock_code_listItem.dart';

import '../../../data/datasource/local/database.dart';
import '../../condition/controllers/buy_conditions_controller.dart';
import '../controllers/stock_list_controller.dart';



class StockListView extends StatefulWidget {
  StockListView({super.key});

  @override
  State<StockListView> createState() => _StockListViewState();
}

class _StockListViewState extends State<StockListView> {
  final StockListController controller = Get.put(StockListController());
  final BuyConditionsController conditionsController =
  Get.find<BuyConditionsController>();
  BuyCondition? _selectedCondition;
  bool _isFirstLoad = true;

  @override
  void initState() {
    super.initState();

    Timer(Duration(seconds: 1), () {
      setState(() {
        _initializeData();
      });
    });
  }

  Future<void> _initializeData() async {
    // 加载买入条件
    await conditionsController.loadBuyConditions();

    // 设置默认选择第一个条件
    if (conditionsController.buyConditions.isNotEmpty && _isFirstLoad) {
      setState(() {
        _selectedCondition = conditionsController.buyConditions.first;
        _isFirstLoad = false;
      });

      // 告诉控制器要使用条件筛选模式
      controller.setFilterCondition(_selectedCondition!);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Obx(() {
          if (controller.isControllerClosed) {
            return const Text('股票列表');
          }
          return Row(
            children: [
              const Text('股票列表'),
              const SizedBox(width: 8),
              if (controller.isTradingTime)
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 4,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.green,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: const Text(
                    '交易中',
                    style: TextStyle(fontSize: 12, color: Colors.white),
                  ),
                ),
            ],
          );
        }),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () {
              if (controller.isControllerClosed) return;

              // 修改刷新逻辑
              if (_selectedCondition != null) {
                // 如果有筛选条件，重新应用筛选
                controller.setFilterCondition(_selectedCondition!);
              } else {
                // 如果没有筛选条件，普通刷新
                controller.refreshData();
              }
            },
          ),
        ],
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              decoration: const InputDecoration(
                labelText: '搜索股票代码或名称',
                prefixIcon: Icon(Icons.search),
                border: OutlineInputBorder(),
              ),
              onChanged: (value) {
                if (value.length > 5) {
                  controller.clearFilter();
                  if (controller.isControllerClosed) return;
                  controller.searchStock(value);
                }
              },
            ),
          ),

          // 条件选择行
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8.0),
            child: Row(
              children: [
                Expanded(
                  child: Obx(() {
                    if (controller.isControllerClosed) {
                      return DropdownButtonFormField<BuyCondition>(
                        value: null,
                        decoration: const InputDecoration(
                          labelText: '选择买入条件',
                          border: OutlineInputBorder(),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 12,
                            vertical: 8,
                          ),
                        ),
                        items: [],
                        onChanged: (BuyCondition? value) {},
                      );
                    }

                    final conditions = conditionsController.buyConditions;

                    // 构建下拉菜单项，将"显示全部"放在最后
                    final List<DropdownMenuItem<BuyCondition>> items = [
                      // 先添加所有条件项
                      ...conditions.map((condition) {
                        return DropdownMenuItem<BuyCondition>(
                          value: condition,
                          child: Text(condition.conditionName),
                        );
                      }).toList(),
                      // 最后添加"显示全部"选项
                      const DropdownMenuItem<BuyCondition>(
                        value: null,
                        child: Text('显示全部'),
                      ),
                    ];

                    return DropdownButtonFormField<BuyCondition>(
                      value: _selectedCondition,
                      decoration: const InputDecoration(
                        labelText: '选择买入条件',
                        border: OutlineInputBorder(),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 8,
                        ),
                      ),
                      items: items,
                      onChanged: (BuyCondition? value) {
                        if (controller.isControllerClosed) return;

                        setState(() {
                          _selectedCondition = value;
                          if (value != null) {
                            // 应用筛选条件并立即加载数据
                            controller.setFilterCondition(value);
                          } else {
                            // 如果选择"显示全部"，则清空筛选结果并刷新普通数据
                            controller.clearFilter();
                            controller.refreshData();
                          }
                        });
                      },
                    );
                  }),
                ),
              ],
            ),
          ),

          // 显示筛选模式下的加载状态
          Obx(() {
            if (controller.isControllerClosed || !controller.hasFilter) {
              return const SizedBox.shrink();
            }

            return controller.isLoading.value
                ? const LinearProgressIndicator()
                : const SizedBox.shrink();
          }),

          // 修复这里：直接使用可观察变量而不是赋值给局部变量
          Obx(() {
            if (controller.isControllerClosed) {
              return const SizedBox.shrink();
            }

            // 直接使用可观察变量，不要赋值给局部变量
            return controller.isTradingTime
                ? Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Text(
                    '自动刷新: ${controller.refreshCount}次',
                    style: const TextStyle(
                      fontSize: 12,
                      color: Colors.grey,
                    ),
                  ),
                  const SizedBox(width: 8),
                  const Icon(
                    Icons.autorenew,
                    size: 16,
                    color: Colors.green,
                  ),
                ],
              ),
            )
                : const SizedBox.shrink();
          }),
          Expanded(
            child: NotificationListener<ScrollNotification>(
              onNotification: (scrollNotification) {
                // 监听滚动事件，更新可见项
                if (!controller.isControllerClosed) {
                  controller.updateVisibleSymbols();
                }
                return false;
              },
              child: Obx(() {
                if (controller.isControllerClosed) {
                  return const Center(child: Text('控制器已关闭'));
                }

                // 确定要显示的股票列表
                final displayStocks =
                controller.hasFilter
                    ? controller.filteredStocks
                    : controller.stockCodes;

                if (controller.isLoading.value && displayStocks.isEmpty) {
                  return const Center(child: CircularProgressIndicator());
                }

                // 在筛选模式下，如果没有数据，显示一个加载下一页的按钮
                if (displayStocks.isEmpty) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        if (!controller.hasMoreData)
                          const Text('已加载所有数据，没有符合条件的股票'),
                      ],
                    ),
                  );
                }

                return Column(
                  children: [
                    Expanded(
                      child: ListView.builder(
                        key: controller.listViewKey, // 设置ListView的Key
                        controller: controller.scrollController,
                        itemCount: displayStocks.length,
                        itemBuilder: (context, index) {
                          final stockCode = displayStocks[index];

                          return StockCodeListItem(
                            key: Key(stockCode.symbol), // 使用symbol作为Key
                            stockCode: stockCode,
                          );
                        },
                      ),
                    ),
                  ],
                );
              }),
            ),
          ),

          //在筛选模式下添加加载更多按钮 - 总是显示，即使没有数据
          if (controller.hasFilter)
            Obx(() {
              // 直接使用可观察变量，不要赋值给局部变量
              return Row(
                children: [
                  const SizedBox(width: 6),
                  // 第一列：页码指示器
                  Text(
                    '第${controller.currentPage}页/共${controller.totalPages}页',
                    style: TextStyle(fontSize: 14, color: Colors.blue),
                  ),

                  const SizedBox(width: 6),
                  // 第二列：已处理进度文本
                  Text(
                    '已处理${controller.processedStocksCount}/${controller.listingDateFilteredCount}只股票',
                    style: TextStyle(fontSize: 12, color: Colors.orange),
                  ),

                  // 留下一个SizedBox作为间隔
                  const SizedBox(width: 20),
                  if (controller.isLoadMore.value)
                    const CircularProgressIndicator()
                  else
                  // 注意：这里原本是Column，现在Row中，我们直接返回一个按钮或文本，并且要考虑在Row中的位置。
                  // 如果controller.hasMoreData是true，则显示加载按钮，否则显示文本。
                    controller.hasMoreData
                        ? IconButton(
                      icon: const Icon(Icons.navigate_next_rounded),
                      onPressed: controller.isControllerClosed
                          ? null
                          : () => controller.loadNextPageWithFilter(),
                    )
                        : const Text(
                      '已是最后一页',
                      style: TextStyle(color: Colors.grey),
                    ),
                ],
              );
            }),
        ],
      ),
    );
  }
}